package com.java.second_goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.second_goods.entity.Booking;
import com.java.second_goods.entity.Review;
import com.java.second_goods.entity.ReviewImage;
import com.java.second_goods.mapper.BookingMapper;
import com.java.second_goods.mapper.ChefMapper;
import com.java.second_goods.mapper.ReviewImageMapper;
import com.java.second_goods.mapper.ReviewMapper;
import com.java.second_goods.service.ChefService;
import com.java.second_goods.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 评价 服务层实现
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private ReviewImageMapper reviewImageMapper;

    @Autowired
    private BookingMapper bookingMapper;

    @Autowired
    private ChefMapper chefMapper;

    @Autowired
    private ChefService chefService;

    /**
     * 查询评价信息
     *
     * @param id 评价ID
     * @return 评价信息
     */
    @Override
    public Review selectReviewById(Integer id) {
        Review review = reviewMapper.selectById(id);
        if (review != null) {
            // 查询关联的图片
            List<ReviewImage> images = reviewImageMapper.selectImagesByReviewId(id);
            review.setImages(images);
        }
        return review;
    }

    /**
     * 根据订单ID查询评价
     *
     * @param bookingId 订单ID
     * @return 评价信息
     */
    @Override
    public Review selectReviewByBookingId(String bookingId) {
        Review review = reviewMapper.selectReviewByBookingId(bookingId);
        if (review != null) {
            // 查询关联的图片
            List<ReviewImage> images = reviewImageMapper.selectImagesByReviewId(review.getId());
            review.setImages(images);
        }
        return review;
    }

    /**
     * 查询评价列表
     *
     * @param review 评价信息
     * @return 评价集合
     */
    @Override
    public List<Review> selectReviewList(Review review) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        if (review.getChefId() != null) {
            queryWrapper.eq(Review::getChefId, review.getChefId());
        }
        if (review.getUserId() != null) {
            queryWrapper.eq(Review::getUserId, review.getUserId());
        }
        if (review.getBookingId() != null) {
            queryWrapper.eq(Review::getBookingId, review.getBookingId());
        }
        // 按评价时间降序
        queryWrapper.orderByDesc(Review::getCreateTime);

        List<Review> reviews = reviewMapper.selectList(queryWrapper);

        // 查询评价图片
        for (Review r : reviews) {
            List<ReviewImage> images = reviewImageMapper.selectImagesByReviewId(r.getId());
            r.setImages(images);
        }

        return reviews;
    }

    /**
     * 根据厨师ID查询评价列表
     *
     * @param chefId 厨师ID
     * @return 评价列表
     */
    @Override
    public List<Review> selectReviewsByChefId(Integer chefId) {
        List<Review> reviews = reviewMapper.selectReviewsByChefId(chefId);

        // 查询评价图片
        for (Review review : reviews) {
            List<ReviewImage> images = reviewImageMapper.selectImagesByReviewId(review.getId());
            review.setImages(images);
        }

        return reviews;
    }

    /**
     * 根据用户ID查询评价列表
     *
     * @param userId 用户ID
     * @return 评价列表
     */
    @Override
    public List<Review> selectReviewsByUserId(Integer userId) {
        List<Review> reviews = reviewMapper.selectReviewsByUserId(userId);

        // 查询评价图片
        for (Review review : reviews) {
            List<ReviewImage> images = reviewImageMapper.selectImagesByReviewId(review.getId());
            review.setImages(images);
        }

        return reviews;
    }

    /**
     * 新增评价
     *
     * @param review 评价信息
     * @param images 评价图片列表
     * @return 结果
     */
    @Override
    @Transactional
    public int insertReview(Review review, List<String> images) {
        // 插入评价
        int rows = reviewMapper.insert(review);

        // 插入评价图片
        if (images != null && !images.isEmpty()) {
            insertReviewImages(review.getId(), images);
        }

        // 更新订单评价状态
        Booking booking = new Booking();
        booking.setId(review.getBookingId());
        booking.setHasReviewed(true);
        bookingMapper.updateById(booking);

        // 更新厨师评分
        Double avgRating = getChefAvgRating(review.getChefId());
        if (avgRating != null) {
            chefService.updateChefRating(review.getChefId(), avgRating);
        }

        return rows;
    }

    /**
     * 修改评价
     *
     * @param review 评价信息
     * @param images 评价图片列表
     * @return 结果
     */
    @Override
    @Transactional
    public int updateReview(Review review, List<String> images) {
        // 更新评价
        int rows = reviewMapper.updateById(review);

        // 更新评价图片
        if (images != null) {
            // 删除旧图片
            reviewImageMapper.deleteImagesByReviewId(review.getId());

            // 插入新图片
            if (!images.isEmpty()) {
                insertReviewImages(review.getId(), images);
            }
        }

        // 更新厨师评分
        Double avgRating = getChefAvgRating(review.getChefId());
        if (avgRating != null) {
            chefService.updateChefRating(review.getChefId(), avgRating);
        }

        return rows;
    }

    /**
     * 删除评价信息
     *
     * @param id 评价ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteReviewById(Integer id) {
        Review review = reviewMapper.selectById(id);
        if (review != null) {
            // 删除评价图片
            reviewImageMapper.deleteImagesByReviewId(id);

            // 删除评价
            int rows = reviewMapper.deleteById(id);

            // 更新订单评价状态
            Booking booking = new Booking();
            booking.setId(review.getBookingId());
            booking.setHasReviewed(false);
            bookingMapper.updateById(booking);

            // 更新厨师评分
            Double avgRating = getChefAvgRating(review.getChefId());
            if (avgRating != null) {
                chefService.updateChefRating(review.getChefId(), avgRating);
            }

            return rows;
        }

        return 0;
    }

    /**
     * 批量删除评价信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteReviewByIds(Integer[] ids) {
        // 获取评价信息
        List<Review> reviews = reviewMapper.selectBatchIds(Arrays.asList(ids));

        // 删除评价图片
        for (Integer id : ids) {
            reviewImageMapper.deleteImagesByReviewId(id);
        }

        // 删除评价
        int rows = reviewMapper.deleteBatchIds(Arrays.asList(ids));

        // 更新订单评价状态
        for (Review review : reviews) {
            Booking booking = new Booking();
            booking.setId(review.getBookingId());
            booking.setHasReviewed(false);
            bookingMapper.updateById(booking);

            // 更新厨师评分
            Double avgRating = getChefAvgRating(review.getChefId());
            if (avgRating != null) {
                chefService.updateChefRating(review.getChefId(), avgRating);
            }
        }

        return rows;
    }

    /**
     * 根据评价ID查询图片
     *
     * @param reviewId 评价ID
     * @return 图片列表
     */
    @Override
    public List<ReviewImage> selectImagesByReviewId(Integer reviewId) {
        return reviewImageMapper.selectImagesByReviewId(reviewId);
    }

    /**
     * 获取厨师评分
     *
     * @param chefId 厨师ID
     * @return 平均评分
     */
    @Override
    public Double getChefAvgRating(Integer chefId) {
        return reviewMapper.getChefAvgRating(chefId);
    }

    /**
     * 插入评价图片
     *
     * @param reviewId 评价ID
     * @param imageUrls 图片URL列表
     */
    private void insertReviewImages(Integer reviewId, List<String> imageUrls) {
        List<ReviewImage> imageList = new ArrayList<>();

        for (String imageUrl : imageUrls) {
            ReviewImage image = new ReviewImage();
            image.setReviewId(reviewId);
            image.setImageUrl(imageUrl);
            imageList.add(image);
        }

        if (!imageList.isEmpty()) {
            reviewImageMapper.batchInsertImages(imageList);
        }
    }
}